//
//  DVTest.m
//  DVmysqlApp
//
//  Created by mt-007 on 2021/4/9.
//

#import <Foundation/Foundation.h>
#import "DVTest.h"

@implementation DVTest

/**
 * @brief init base databases connect information and connect.
 */
- (instancetype)initDBBaseInfo {
    if(self = [super init]){
        /** GET connect information. */
        pFilePath = [[NSBundle mainBundle] pathForResource:@"DBInfo" ofType:@"plist"];
        pData = [[NSMutableDictionary alloc] initWithContentsOfFile:pFilePath];
        NSLog(@"%@", pData);
        /** SET connect information and connect databases*/
        usr = [[OHMySQLUser alloc]initWithUserName:pData[@"dbUserName"]
                                          password:pData[@"dbUserPassword"]
                                        serverName:pData[@"dbServerName"]
                                            dbName:pData[@"dbName"]
                                              port:[pData[@"dbServerPort"] unsignedIntValue]
                                            socket:nil];
        coordinator = [[OHMySQLStoreCoordinator alloc]initWithUser:usr];
        
        /** connect to mysql server*/
        [coordinator connect];
    }
    return self;
}



/**
 * @brief test coordinator connect status, it will use NSLog to display.
 * there are 4 case:
 *  1. Connect databases successful.
 *  2. Databases server lost.
 *  3. MySQL server gone.
 *  4. Unknow error type.
 */
- (void)coordinatorTest {
    if(coordinator.isConnected == YES){
        switch ([coordinator pingMySQL]) {
            case OHResultErrorTypeNone:
                NSLog(@"数据库连接成功");
                break;
            case OHResultErrorTypeLost:
                NSLog(@"与服务器连接丢失");
                break;
            case OHResultErrorTypeGone:
                NSLog(@"MYSQL服务器已经消失了");
                break;
            case OHResultErrorTypeUnknown:
                NSLog(@"未知错误");
                break;
            default:
                break;
        }
    }
}


/**
 * @brief Query all informationn for signal table;
 *
 * @param selectTable select a table to query.
 *
 * @return A query task, as array[i][j] it's 2D array.
 */
- (NSArray *)queryTaskForAll:(NSString *)selectTable {
    // init device upload and download
    OHMySQLQueryContext *queryContext = [OHMySQLQueryContext new];
    queryContext.storeCoordinator = coordinator;
    
    OHMySQLQueryRequest *query = [OHMySQLQueryRequestFactory SELECT:@"s_table" condition:nil orderBy:@[@"s_id"] ascending:YES];

    
    NSError *error = nil;
    
    NSArray *task = [queryContext executeQueryRequestAndFetchResult:query error:&error];
    
    return task;
}

- (void)displayTask:(NSArray *)task {
    if(task == nil) {
        return;
    }
    for(NSArray *i in task) {
        NSLog(@"%@", i);
    }
}

/**
 * Coordinator disconnect.
 */
- (void)close {
    NSLog(@"close db connect.");
    [coordinator disconnect];
}

@end
